<?php

namespace Home\Controller;
// use Utuo\ForegroundController;
// use Utuo\Sms;
use Utuo\WechatAdvance;
use Home\Logic\DistributionShopRedPacketLogic;
use Utuo\DisShopForegroundController;
use Utuo\ForegroundController;
use Utuo\DBRW;
use My\Model\DistributionShopOrderModel;
use Api\Tools\QrcodeUtil;
use Utuo\WechatAdvance\QrCode;
use Utuo\WechatAdvance\Media;
use My\Model\WechatUserModel;
use My\Model\UserRole;
use Utuo\Region;
use My\Model\DeliveryModel;
use Utuo\DistributionShopScore;
use Home\Logic\GoodsLogic;
use Home\Logic\ScoreEventLogic;
use Utuo\WechatUserLogin;

class TestoController extends ForegroundController {
    
     public function asdAction() {
         echo <<<Tag
       <embed wmode="window" flashvars="vid=t0154kzy3uk&amp;tpid=3&amp;showend=1&amp;showcfg=1&amp;searchbar=1&amp;shownext=1&amp;list=2&amp;autoplay=1&amp;outhost=http%3A%2F%2Fv.qq.com%2Fboke%2Fpage%2Ft%2F0%2Fk%2Ft0154kzy3uk.html&amp;openbc=0&amp;title=%20%E5%A4%AE%E8%A7%86%E6%AD%A3%E5%BC%8F%E8%82%AF%E5%AE%9A%E5%BE%AE%E5%95%86%20%E5%BE%AE%E5%95%86%E5%9B%BD%E9%99%85%E8%93%AC%E5%8B%83%E5%8F%91%E5%B1%95" src="http://imgcache.qq.com/tencentvideo_v1/player/TencentPlayer.swf?max_age=86400&amp;v=20140714" quality="high" name="tenvideo_flash_player_1432111980772" id="tenvideo_flash_player_1432111980772" bgcolor="#000000" width="650px" height="472px" align="middle" allowscriptaccess="always" allowfullscreen="true" type="application/x-shockwave-flash" pluginspage="http://get.adobe.com/cn/flashplayer/">  
Tag;
     }
     
     public function asddAction() {
             $this->authId = 1;
             $openId = 'oIoTWjua2ih8sgLaW-YJzRWy_2IM';
             /* 设置登录接口 */
             $login = WechatUserLogin::newInstance(array(
                 'cid' => $this->authId,
             ));
			    $shopConfig = D("My/DistributionShop")->getShopConfig($this->authId);
				if ( !empty($shopConfig) and !empty($shopConfig['status']) and $shopConfig['status']) {
				    $result = ScoreEventLogic::checkStatus($shopConfig, 'DownlineSubscribe');
				    if ( $result['check'] ) {
				        $wechatUser = $login->bindUser(array('openId' => $openId, ));
				        if ( $wechatUser ) {
				            $scoreHandle = DistributionShopScore::getInstance("DownlineSubscribe", array('cid'=>$this->authId, 'uid' => $wechatUser['mid']), $result['driverConfig']);
				            $scoreHandle->exec();
				            echo "234234";
				        }
				    }
				}
     }
    
    public function testAction( ) {
        $this->uid = 263370;
        $this->cid = 250;
        $shopGoods = (unserialize('a:49:{s:2:"id";s:2:"85";s:3:"cid";s:3:"250";s:4:"name";s:21:"缪斯女神约会霜";s:3:"tag";s:0:"";s:5:"brand";N;s:10:"efficiency";s:0:"";s:4:"sort";s:1:"1";s:5:"price";s:4:"0.00";s:10:"high_price";s:6:"168.00";s:12:"dealer_price";s:4:"0.00";s:9:"try_price";s:4:"0.00";s:5:"total";s:4:"2000";s:11:"description";s:256:"十秒迅速全身变白，天然养肤告别粗糙，精致女人的必备武器。本周五上午9:30分，零元抢购活动继续进行，但由于节假日以及快递原因，本次活动的产品将在五一小长假结束以后统一安排发出。";s:7:"content";s:1867:"<p><br/></p><p><img src="http://wmei-wmei5.stor.sinaapp.com/upload/20150109/1420771012520949.jpg" style="float:none;" title="约会霜详情图_02.jpg"/><img src="http://wmei-wmei5.stor.sinaapp.com/upload/20150109/1420771014712634.jpg" title="约会霜详情图_03.jpg" style="float: none;"/><img src="http://wmei-wmei5.stor.sinaapp.com/upload/20150109/1420771016426930.jpg" title="约会霜详情图_04.jpg" style="float: none;"/><img src="http://wmei-wmei5.stor.sinaapp.com/upload/20150109/1420771019908285.jpg" title="约会霜详情图_05.jpg" style="float: none;"/></p><p><img src="http://wmei-wmei5.stor.sinaapp.com/upload/20150109/1420771021324022.jpg" style="float:none;" title="约会霜详情图_06.jpg"/><img src="http://wmei-wmei5.stor.sinaapp.com/upload/20150109/1420771023602705.jpg" title="约会霜详情图_07.jpg" style="float: none;"/><img src="http://wmei-wmei5.stor.sinaapp.com/upload/20150109/1420771025606661.jpg" title="约会霜详情图_08.jpg" style="float: none;"/></p><p><img src="http://wmei-wmei5.stor.sinaapp.com/upload/20150109/1420771027101841.jpg" style="float:none;" title="约会霜详情图_09.jpg"/></p><p><img src="http://wmei-wmei5.stor.sinaapp.com/upload/20150109/1420771029801865.jpg" style="float:none;" title="约会霜详情图_10.jpg"/><img src="http://wmei-wmei5.stor.sinaapp.com/upload/20150109/1420771032914307.jpg" title="约会霜详情图_11.jpg" style="float: none;"/></p><p><img src="http://wmei-wmei5.stor.sinaapp.com/upload/20150109/1420771037158963.jpg" style="float:none;" title="约会霜详情图_12.jpg"/></p><p><img src="http://wmei-wmei5.stor.sinaapp.com/upload/20150109/1420771039636032.jpg" style="float:none;" title="约会霜详情图_13.jpg"/><img src="http://wmei-wmei5.stor.sinaapp.com/upload/20150109/1420771041258661.jpg" title="约会霜详情图_14.jpg" style="float: none;"/></p><p><br/></p>";s:10:"saled_base";s:4:"5143";s:11:"saled_count";s:3:"226";s:8:"carriage";s:5:"20.00";s:15:"shipping_tpl_id";s:1:"0";s:15:"shipping_method";s:1:"0";s:15:"shipping_config";a:3:{i:1;s:2:"20";i:2;s:2:"20";i:3;s:2:"20";}s:11:"support_cod";s:1:"0";s:6:"images";a:1:{i:0;s:72:"http://wmei-wmei5.stor.sinaapp.com/2015-01-09/2015010910342629918937.jpg";}s:14:"image_vertical";s:72:"http://wmei-wmei5.stor.sinaapp.com/2015-04-14/2015041414255896499292.jpg";s:11:"image_share";s:72:"http://wmei-wmei5.stor.sinaapp.com/2015-01-09/2015010910345850241839.jpg";s:9:"attrs_cfg";b:0;s:8:"class_id";s:1:"0";s:7:"cate_id";s:1:"0";s:12:"reward_price";s:4:"0.00";s:10:"reward_set";s:1:"0";s:14:"reward_percent";s:8:"50:30:20";s:19:"reward_price_dealer";s:4:"1.00";s:17:"reward_set_dealer";s:1:"1";s:21:"reward_percent_dealer";s:8:"50:30:20";s:13:"reward_price2";s:4:"0.00";s:20:"reward_price2_dealer";s:4:"0.00";s:3:"try";s:1:"0";s:20:"try_collection_count";s:1:"5";s:11:"limit_count";s:1:"0";s:9:"limit_buy";s:1:"0";s:10:"is_seckill";s:1:"0";s:12:"begin_method";s:1:"0";s:14:"timing_shelves";s:1:"0";s:12:"donate_money";s:4:"0.00";s:11:"create_time";s:10:"1420771123";s:6:"status";s:1:"1";s:10:"is_deleted";s:1:"0";s:3:"pic";s:72:"http://wmei-wmei5.stor.sinaapp.com/2015-01-09/2015010910342629918937.jpg";s:18:"selectedAttributes";N;s:12:"productPrice";d:0;}'));
        $res = $this->getPercentAndUsers($shopGoods);
        $dealer = $res['dealer'];
        $franchisedDealerUids = $dealer[0];
        $rewardPercentDealer = $dealer[1];
        $rewardPriceDealer = $dealer[2];
        
        $rewardBonusDealer = DistributionShopOrderModel::calcSimpleRewardBonus($franchisedDealerUids, $rewardPercentDealer, 1*$rewardPriceDealer);
        dump($rewardBonusDealer);
    }

    /**
     * 获得订单中一个产品的分成比例与分成用户
     * @param array $shopGoods 所买商品
     * @param array $orderGoodsItem 订单商品（支付前的订单商品格式,即getItems的格式）
     * @return multitype:multitype:multitype: unknown
     */
    protected function getPercentAndUsers( $shopGoods, $orderGoodsItem = array() ) {
    
        /* 基础佣金 */
        $rewardPrice = $shopGoods['reward_price']; // 基础佣金
    
        /* 特约经销商佣金 */
        $rewardPriceDealer = $shopGoods['reward_price_dealer']; // 特约经销商佣金
    
        /* 特约经销购买时 */
        $userRole = new UserRole();
        if ( $userRole->type($this->user['type'])->is(WechatUserModel::USER_TYPE_FRANCHISED_DEALER) ) { // 特约经销商
            if ( $shopGoods['dealer_price']*1 and $shopGoods['dealer_price'] - $orderGoodsItem['productPrice'] == 0 ) { // (当前金牌会员价-拍下价格=0)以金牌会员价购买更改佣金
                $rewardPrice = $shopGoods['reward_price2'];
                $rewardPriceDealer = $shopGoods['reward_price2_dealer'];
            }
        }
    
        /* 基础分成发放比例 */
        $rewardPercent = array();
        if ( $shopGoods['reward_set'] ) { // 商品设置的分成比例
            $shopGoods['reward_percent'] and $rewardPercent = explode(':', $shopGoods['reward_percent']);
        } else { // 系统默认分成比例
            $this->config['reward_percent'] and $rewardPercent = explode(':', $this->config['reward_percent']);
        }
    
        /* 获得参与佣金发放的用户  */
        $tree = M("DistributionShopUserTree")->where(array('cid'=>$this->cid, 'uid'=>$this->uid))->getField("tree");
        $uids = explode(',', $tree);
        array_shift($uids);
    
        /* 特约经销商分成发放比例  */
        $rewardPercentDealer = array();
        if ( $shopGoods['reward_set_dealer'] ) { // 商品设置的分成比例
            $shopGoods['reward_percent_dealer'] and $rewardPercentDealer = explode(':', $shopGoods['reward_percent_dealer']);
        } else { // 系统默认分成比例
            $this->config['reward_percent_dealer'] and $rewardPercentDealer = explode(':', $this->config['reward_percent_dealer']);
        }
    
        /** 用户筛选出特约与基础用户(固位模式筛选) */
        $userRole = new UserRole();
        $baseUids = array(); // 基础用户
        $franchisedDealerUids = array(); // 特约经销商
        $userInfo = array();
        if ( $uids ) {
            $userInfo = M("WechatUser")->where(array('id'=>array('in', $uids)))->order("find_in_set(id, '{$tree}')")->getField("id,type");
            for ( $i=0; $i < count($uids); $i++ ) {
                /* 初始值设定位置分成用户0 */
                $baseUids[$i] = 0;
                $franchisedDealerUids[$i] = 0;
                if ( $userRole->type($userInfo[$uids[$i]])->is(WechatUserModel::USER_TYPE_AGENT) ) { // 代理用户
                    // 代理商
                }
                if ( $userRole->type($userInfo[$uids[$i]])->is(WechatUserModel::USER_TYPE_FRANCHISED_DEALER) ) { // 筛选特约经销商用户 (从非代理用户)
                    $franchisedDealerUids[$i] = $uids[$i];
                }
                if ( $userRole->type($userInfo[$uids[$i]])->is(WechatUserModel::USER_TYPE_STANDARD) ) { // 普通会员
                    $baseUids[$i] = $uids[$i];
                }
            }
        }
    
        /* 基础分成用户与分成比例 */
        $baseUids = array_slice($baseUids, 0, count($rewardPercent)); // 分配比例 -> 裁剪分销用户
        $rewardPercent = array_slice($rewardPercent, 0, count($baseUids));  // 分销用户 -> 裁剪分配比例
        $uidCount = count($baseUids);
        for( $i = 0; $i < $uidCount; $i++ ) { // 清除uid为0的用户
            if ( !$baseUids[$i]*1 ) {
                unset($baseUids[$i]);
                unset($rewardPercent[$i]);
            }
        }
    
        /* 用户与分成比例 (特约经销商)*/
        $franchisedDealerUids = array_slice($franchisedDealerUids, 0, count($rewardPercentDealer)); // 分配比例 -> 裁剪分销用户
        $rewardPercentDealer = array_slice($rewardPercentDealer, 0, count($franchisedDealerUids));  // 分销用户 -> 裁剪分配比例
        $uidCount = count($franchisedDealerUids);
        for( $i = 0; $i < $uidCount; $i++ ) { // 清除uid为0的用户
            if ( !$franchisedDealerUids[$i]*1 ) {
                unset($franchisedDealerUids[$i]);
                unset($rewardPercentDealer[$i]);
            }
        }
    
        return array(
            'base' => array($baseUids, $rewardPercent, $rewardPrice),
            'dealer' => array($franchisedDealerUids, $rewardPercentDealer, $rewardPriceDealer),
        );
    }
    
    
    
    public function testAgentModeAction() {
        $wparam['aid'] = 684;
        $this->authId = 250;
        $goodsSurplus = 199.00;
        $shopConfig = D("My/DistributionShop")->getShopConfig($this->authId);
        $agentShopConfig = $shopConfig["agent_shop_config"];
        $modeConfig = $agentShopConfig['modeConfig'][0];
        if ( $modeConfig['agent_reward_percent'] ) {
            if ( !$this->agentLayerTree ) {
                // 获得层级树
                $seller = $agent = M("Agent")->where("id=%d", $wparam['aid'] )->find(); // 代理商
                if ( $seller ) {
                    $curlevel = $seller['level']*1; // 代理商等级
                    $agentLayerTree = $seller['id']; // 层级树
                    while ( $agent['parent_id']*1 != 0 ) {
                        $agent = M("Agent")->where("id=%d", $agent['parent_id'] )->find(); // 上级代理商
                        $spaceLevel = $curlevel - $agent['level'] - 1;
                        for ( $i=0; $i<$spaceLevel; $i++ ) {
                            $agentLayerTree.=",0";
                        }
                        $agentLayerTree.= ",{$agent['id']}";
                        $curlevel = $agent['level'];
                    }
                    if ( $curlevel ) {
                        $spaceLevel = $curlevel;
                        for ( $i=0; $i<$spaceLevel; $i++ ) {
                            $agentLayerTree.=",0";
                        }
                    }
                    $this->agentLayerTree = $agentLayerTree.",s";
                } else {
                    $this->agentLayerTree = "s";
                }
            }
            $altArray = array_reverse(explode(",", $this->$agentLayerTree)); // 分佣树 s,0,....
            $percentArray =  explode(":", $modeConfig['agent_reward_percent']); // 分佣比例 s,0,....
            /* 补齐与裁剪 */
            if ( count($altArray) < count($percentArray) ) {
                $altArray = array_pad($altArray, count($percentArray), 0); // 补齐代理
            } elseif ( count($altArray) > count($percentArray) ) {
                $altArray = array_slice($altArray, 0, count($percentArray)); // 裁剪代理层级树
            }
            /* 合并比例(无用户并入邻近上级) */
            for( $i=count($altArray)-1; $i>0; $i--) {
                if ( $altArray[$i] == 0 and isset($altArray[$i-1]) ) {
                    $percentArray[$i-1] += $percentArray[$i];
                    $percentArray[$i] = 0;
                }
            }
            /* 盈余再次给厂家与代理分成 */
            $rewardBonusAgent = array();
            foreach ( $percentArray as $v ) {
                $rewardBonusAgent[] = $goodsSurplus*($v/100);
            }
            $orderGoodsItem['reward_total_agent'] = $goodsSurplus;
            $orderGoodsItem['reward_aids_agent'] = join(",", $altArray);
            $orderGoodsItem['reward_percent_agent'] = join(":", $percentArray);
            $orderGoodsItem['reward_bonus_agent'] = join(",", $rewardBonusAgent);
        }
        dump($orderGoodsItem);
    }
    
    public function testSendMsgAction() {
        $orderId = '1505301513200003216637';
        $this->wechatAdvance = new WechatAdvance('wx98c4c26a2e5edcba', '21a2aa3832066d16a07e9626d7b2fd3c');
        $productOrder = M("DistributionShopOrder")->where("order_id='%s'", $orderId)->find();
        /* 代理分销发送消息提醒 */
        if ( !empty($productOrder['reward_aids']) ) {
            $agentBonus = array_combine(explode(',', $productOrder['reward_aids']), explode(',', $productOrder['reward_bonus_agent']));
            dump($productOrder['reward_aids']);
            dump($productOrder['reward_bonus_agent']);
            foreach ( $agentBonus as $aid => $v ) {
                $aid == 's' and $aid = 0;
                if ( $aid ) {
                    echo $aid;
                    $tmpAgent = M("Agent")->where("id=%d", $aid)->find();
                    if ( $tmpAgent ) {
                        $tmpUser = M("WechatUser")->where("id=%d", $tmpAgent['wechat_uid'])->find();
                        if ( $tmpUser ) {
                            /* 发送支付成功消息 */
                            $this->sendServerMsg($tmpUser['openId'], array(
                                'content' => '您分销的订单'.$orderId."买家:{$tmpUser['nickname']}已支付,预计买家确认收货后您将获得￥{$v}元分成",
                            ));
                        }
                    }
                }
            }
        }
    }
    
    /**
     * 发送客服消息
     * @param unknown $openId
     * @param unknown $msg
     */
    private function sendServerMsg( $openId, $data, $type = 0 ) {
        dump($openId);
        dump($data);
        echo "<br/>";
        $accessToken = $this->wechatAdvance->getBaseAccess();
        $this->wechatAdvance->sendServerMessage( $accessToken['access_token'], $openId, $data, $type );
    }
    
    
    

}
